<template>
  <DtModal @register="register" @save="handUpload">
    <div class="dt-cropper-modal">
      <div :class="`${prefixCls}-left`">
        <div :class="`${prefixCls}-cropper`">
          <CropperWrap
              v-if="src"
              v-bind="props"
              :src="src"
              @cropend="handleCropend"
              @ready="handleReady"
          ></CropperWrap>
        </div>

        <div :class="`${prefixCls}-toolbar`">
          <AUpload
              :fileList="[]"
              accept="image/*"
              :beforeUpload="handleBeforeUpload"
          >
            <ATooltip title="选择图片" placement="bottom">
              <AButton type="primary" :size="'small'">
                <i class="i ic:baseline-file-upload"></i>
              </AButton>
            </ATooltip>
          </AUpload>

          <ASpace>
            <ATooltip title="重置">
              <AButton type="primary" :size="'small'" :disabled="!src" @click="handlerToolbar('reset')">
                <i class="i ic:baseline-autorenew"></i>
              </AButton>
            </ATooltip>

            <ATooltip title="逆时针旋转">
              <AButton type="primary" :size="'small'" :disabled="!src" @click="handlerToolbar('rotate', -45)">
                <i class="i ic:baseline-rotate-left"></i>
              </AButton>
            </ATooltip>

            <ATooltip title="顺时针旋转">
              <AButton type="primary" :size="'small'" :disabled="!src" @click="handlerToolbar('rotate', 45)">
                <i class="i ic:baseline-rotate-right"></i>
              </AButton>
            </ATooltip>

            <ATooltip title="水平翻转">
              <AButton type="primary" :size="'small'" :disabled="!src" @click="handlerToolbar('scaleX')">
                <i class="i mdi:arrow-expand-horizontal"></i>
              </AButton>
            </ATooltip>

            <ATooltip title="垂直翻转">
              <AButton type="primary" :size="'small'" :disabled="!src" @click="handlerToolbar('scaleY')">
                <i class="i ant-design:column-height-outlined"></i>
              </AButton>
            </ATooltip>

            <ATooltip title="放大">
              <AButton type="primary" :size="'small'" :disabled="!src" @click="handlerToolbar('zoom', 0.1)">
                <i class="i ic:baseline-zoom-in"></i>
              </AButton>
            </ATooltip>

            <ATooltip title="缩小">
              <AButton type="primary" :size="'small'" :disabled="!src" @click="handlerToolbar('zoom', -0.1)">
                <i class="i ic:baseline-zoom-out"></i>
              </AButton>
            </ATooltip>
          </ASpace>
        </div>
      </div>

      <div :class="`${prefixCls}-right`">
        <div :class="`${prefixCls}-preview`">
          <div :style="getPreviewStyle">
            <img :src="previewSource" v-if="previewSource" alt="图片预览" />
          </div>
        </div>
        <ADivider></ADivider>

        <p class="desc">{{ props?.desc }}</p>
      </div>
    </div>
  </DtModal>
</template>

<script lang="ts" setup>
import { useModal } from '@zm-pkg/ui'
import { default as CropperWrap } from './CropperWrap.vue'
import type Cropper from 'cropperjs'
import { Recordable } from '@zm-pkg/core'
import { CSSProperties } from 'vue'


const prefixCls = 'dt-cropper-modal'
const props = ref<Recordable>({})
const emits = defineEmits(['register'])

let filename = ''
let scaleX = 1, scaleY = 1

const src = ref('')
const previewSource = ref('')
const cropper = ref<Cropper>()

const getPreviewStyle = computed((): CSSProperties => {
  const { aspectRatio } = unref(props)?.options??{}

  let circledStyle = {}

  if( unref(props)?.circled ) {
    circledStyle = {
      borderRadius: '50%'
    }
  }

  if( !aspectRatio ) return {
    ...circledStyle
  }

  if( aspectRatio > 1 ) {
    return {
      ...circledStyle,
      width: '100%',
      height: `calc(100% / ${ aspectRatio })`
    }
  } else {
    return {
      ...circledStyle,
      width: `calc(100% / ${ aspectRatio })`,
      height: `100%`
    }
  }
})

const [register, { closeModal }] = useModal({
  title: '图片裁剪',
  width: '800px',
  canFullscreen: false,
  minHeight: 340
}, (options) => {
  props.value = options
})

function handleCropend({ imgBase64 }) {
  previewSource.value = imgBase64
}

function handleReady(cropperInstance: Cropper) {
  cropper.value = cropperInstance
}

function handlerToolbar(event: string, arg?: number) {
  if (event === 'scaleX') {
    scaleX = arg = scaleX === -1 ? 1 : -1
  }
  if (event === 'scaleY') {
    scaleY = arg = scaleY === -1 ? 1 : -1
  }
  cropper?.value?.[event]?.(arg)

}

function handleBeforeUpload(file: File) {
  const reader = new FileReader()
  reader.readAsDataURL(file)
  src.value = ''
  previewSource.value = ''

  reader.onload = (e) => {
    src.value = (e.target?.result as string) ?? ''
    filename = file.name
  }

  return false
}


// 文件开始上传
function handUpload() {
  closeModal({
    source: previewSource.value,
    data: 0
  })
}

</script>

<style lang="less" scoped>
@prefix-cls: ~'dt-cropper-modal';

.@{prefix-cls}{
  display: flex;

  &-left,
  &-right {
    height: 340px;
  }

  &-left {
    width: 55%;
  }

  &-right {
    width: 45%;
  }

  &-cropper {
    height: 300px;
    background: #eee;
    background-image: linear-gradient( 45deg, rgb(0 0 0 / 25%) 25%, transparent 0, transparent 75%,rgb(0 0 0 / 25%) 0),
    linear-gradient( 45deg, rgb(0 0 0 / 25%) 25%, transparent 0, transparent 75%, rgb(0 0 0 / 25%) 0);
    background-position: 0 0, 12px 12px;
    background-size: 24px 24px;
  }

  &-toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 10px;

    i{
      font-size: 16px;
    }
  }

  &-preview {
    width: 220px;
    height: 220px;
    margin: 0 auto;
    display: flex;
    align-items: center;
    justify-content: center;

    & > div{
      border: 1px solid #d9d9d9;
      overflow: hidden;
      display: block;
    }

    img {
      width: 100%;
      height: 100%;
    }
  }


  &-right {
    align-items: stretch;
    padding: 10px 20px;
    .desc{
      opacity: 0.5;
      text-align: center;
    }
  }
}

</style>